﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Windows;
using System.Windows.Input;

namespace Freshome.m.fox
{
    internal sealed class Helproxy<T> where T : class
    {
        private readonly fox.Userole _ur = null;
        public Helproxy(fox.Userole ur)
        {
            this._ur = ur;
        }
        public void Syncall<P>(Action<P> action, P cln) where P : ClientBase<T>
        {
            try
            {
                Mouse.OverrideCursor = Cursors.Wait;
                if (this._ur != null)
                {
                    cln.ClientCredentials.UserName.UserName = _ur.UserName;
                    cln.ClientCredentials.UserName.Password = _ur.UserPass;
                    action(cln);
                }
                cln.Close();
            }
            catch (FaultException ex)
            {
                cln.Abort();
                MessageBox.Show(ex.Message, "服务异常", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (CommunicationException ex)
            {
                cln.Abort();
                MessageBox.Show(ex.Message, "网络故障", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (TimeoutException ex)
            {
                cln.Abort();
                MessageBox.Show(ex.Message, "会话超时", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.Message, "系统异常", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            finally
            {
                Mouse.OverrideCursor = null;
            }
        }
        public void Asyncall<P>(Action<P> action, P cln) where P : ClientBase<T>
        {
            try
            {
                if (this._ur != null)
                {
                    cln.ClientCredentials.UserName.UserName = _ur.UserName;
                    cln.ClientCredentials.UserName.Password = _ur.UserPass;
                    action(cln);
                }
                cln.Close();
            }
            catch (FaultException ex)
            {
                cln.Abort();
                throw new SystemException("服务异常", ex);
            }
            catch (CommunicationException ex)
            {
                cln.Abort();
                throw new SystemException("网络故障", ex);
            }
            catch (TimeoutException ex)
            {
                cln.Abort();
                throw new SystemException("会话超时", ex);
            }
            catch (SystemException ex)
            {
                throw new SystemException("系统异常", ex);
            }
        }
    }
}
